<?php
// +----------------------------------------------------------------------
// | CSMITSM  [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 https://www.fastadmin.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: chenshiming
// +----------------------------------------------------------------------

namespace app\admin\controller\csmitsm;

use think\Db;
use addons\csmitsm\library\xcore\xcore\base\XcABackend;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcConfigUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcAdminTabUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestPathUtils;

/**
 * 主数据
 *
 * @icon fa fa-circle-o
 */
class Xcflowmdm extends XcABackend
{

  /**
   * Xcflowmdm模型对象
   * @var \app\admin\model\csmitsm\Xcflowmdm
   */
  protected $model = null;


  public function _initialize()
  {
    parent::_initialize();
    $this->model = new \app\admin\model\csmitsm\Xcflowmdm;
    $this->assign("haspublishList", $this->model->getHaspublishList());
    $this->assign("statusList", $this->model->getStatusList());
    $this->assign("canmodifyList", $this->model->getCanmodifyList());

    // csmitsm:设置页面tabs
    $xc_tabid = XcRequestUtils::param(["id", "ids", "xc_tabid"]);
    XcAdminTabUtils::append_control_initialize('xcflowmdm', $xc_tabid, __CLASS__, $this->view);
  }

  /**
   * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
   * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
   * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
   */

  public function index()
  {
    //设置过滤方法
    $this->request->filter(['strip_tags', 'trim']);
    if (false === $this->request->isAjax()) {
      return $this->view->fetch();
    }
    //如果发送的来源是 Selectpage，则转发到 Selectpage
    if ($this->request->request('keyField')) {
      return $this->selectpage();
    }
    [$where, $sort, $order, $offset, $limit] = $this->buildparams();
    $list = $this->model
      ->where($where)
      ->where("type", "=", "user_table")
      ->order($sort, $order)
      ->paginate($limit);
    $result = ['total' => $list->total(), 'rows' => $list->items()];
    return json($result);
  }


  public function fieldconfig($ids)
  {
    $addoncode = XcConfigUtils::getAddonCode();
    // $xcbaseurl = XcConfigUtils::config("xcbaseurl") . "/addons/{$addoncode}/xc_flowmdm/";
    $xcbaseurl = XcRequestPathUtils::urlAddons("/xc_flowmdm/");

    $param = ["xcform_id" => $ids, "xccontrol" => "xcform", "xcbaseurl" => $xcbaseurl];

    $url = XcRequestUtils::appendUrlParams("/assets/addons/{$addoncode}/h5_xcflow_xcform/#/", $param);
    $xdebugSrc = XcRequestUtils::appendUrlParams("http://localhost:8080/#/", $param);

    return $this->fetchIframePage($url, $xdebugSrc);
  }

  protected function beforeAddSubmit(&$params)
  {
    $code = strtolower($params['code']);
    $name = strtolower($params['name']);

    // assert code unique 
    if (true) {
      $row = XcDaoUtils::getRowBySql($this->model, [
        ['code', '=', $code]
      ]);
      if ($row) {
        $this->error("编码重复,请更换编码:" . $code);
      }
    }
    // init database flowtable
    $tablename = null;
    if (true) {
      $prefix = ($params['xcformtype'] == 'flowsub') ? "flowsub" : "mdm";
      $tablename = XcDatabaseUtils::appendTablePrefix(XcConfigUtils::getAddonCode() . "_{$prefix}_" . $code);

      if (XcDatabaseUtils::existsTable($tablename)) {
        $this->error("数据表已经存在:" . $tablename);
      }
    }

    if (true) {
      $sql = "
              CREATE TABLE `{$tablename}` (
                   `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',  
                    `xcformtype` varchar(255) DEFAULT NULL COMMENT 'form类型',
                    `xcform_id` int(11) DEFAULT NULL COMMENT 'form id',                         
                   `user_id` int(10) DEFAULT '0' COMMENT '会员ID',
                   `admin_id` int(10) DEFAULT '0' COMMENT '管理员ID',
                   `createtime` bigint(16) DEFAULT NULL COMMENT '创建时间',
                   `updatetime` bigint(16) DEFAULT NULL COMMENT '更新时间',
                   `weigh` int(10) DEFAULT '0' COMMENT '权重',
                   `status` enum('normal','hidden','draft') DEFAULT 'normal' COMMENT '状态:normal=正常,hidden=删除,draft=草稿',
                   PRIMARY KEY (`id`)
               ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='{$name}'
             ";
      Db::execute($sql);
    }

    $params['code'] = $code;
    $params['name'] = $name;
    $params['publishtablename'] = $tablename;
  }

  protected function afterDelSubmit($row)
  {
    $tablename = $row->publishtablename;
    $deleted_publishtablename = "deleted_{$tablename}_{$row->id}";

    Db::execute("RENAME TABLE {$tablename} TO {$deleted_publishtablename};");
    $row->save([
      'publishtablename' => $deleted_publishtablename
    ]);
  }

  public function publishmenu()
  {
    return $this->_publishmenu("csmitsm/xcflowmdmdata/index?xcform_id=[[id]]");
  }
}
